<template>
  <div class="wrapper">
    <header>
      <i class="fa fa-angle-left" @click="goBack"></i>
      <p>钱包充值</p>
    </header>
    <div class="content">
      <div class="section">
        <div class="title">充值金额</div>
        <div class="presets">
          <button v-for="p in presets" :key="p" :class="{active: amount===p}" @click="amount=p">¥{{ p }}</button>
        </div>
        <input type="number" v-model.number="amount" placeholder="自定义金额" @input="checkReward" />
        <div v-if="rewardRule && rewardAmount > 0" class="reward-info">
          <div class="reward-text">🎉 充值奖励：¥{{ formatAmount(rewardAmount) }}</div>
          <div class="reward-desc">{{ rewardRule.ruleName || '充值奖励规则' }}</div>
        </div>
        <div v-else-if="amount > 0" class="reward-info no-reward">
          <div class="reward-text">当前充值金额暂无奖励</div>
        </div>
      </div>
      <div class="section">
        <div class="title">支付方式</div>
        <div class="methods">
          <label><input type="radio" value="alipay" v-model="method" /> 支付宝</label>
          <label><input type="radio" value="wechat" v-model="method" /> 微信</label>
          <label><input type="radio" value="card" v-model="method" /> 银行卡</label>
        </div>
      </div>
      <div class="section">
        <button class="confirm" :disabled="!canSubmit" @click="confirmRecharge">确认充值</button>
      </div>
      <div v-if="lastTxn" class="result">
        <div>本次充值：¥{{ formatAmount(lastTxn.amount - (lastTxn.rewardAmount || 0)) }}</div>
        <div v-if="lastTxn.rewardAmount > 0">获得奖励：¥{{ formatAmount(lastTxn.rewardAmount) }}</div>
        <div>交易号：{{ lastTxn.transactionNo }}</div>
      </div>
    </div>
    <Footer />
  </div>
</template>

<script setup>
import Footer from '../components/Footer.vue'
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { walletApi } from '../api'

const router = useRouter()
const presets = [50, 100, 200, 500]
const amount = ref(100)
const method = ref('alipay')
const lastTxn = ref(null)
const rewardRule = ref(null)
const rewardAmount = ref(0)

const canSubmit = () => Number(amount.value) > 0
const formatAmount = v => Number(v || 0).toFixed(2)

const checkReward = async () => {
  if (!amount.value || amount.value <= 0) {
    rewardRule.value = null
    rewardAmount.value = 0
    return
  }

  try {
    // 按照"每充值100元赠送10元"的规则计算奖励
    // 计算可以赠送多少个10元（每100元一个）
    const rewardMultiplier = Math.floor(amount.value / 100)
    rewardAmount.value = rewardMultiplier * 10

    if (rewardAmount.value > 0) {
      // 创建一个虚拟的规则对象用于显示
      rewardRule.value = {
        ruleName: '每充值100元赠送10元',
        conditionValue: 100,
        ruleValue: 10
      }
    } else {
      rewardRule.value = null
    }
  } catch (e) {
    console.error('计算奖励失败:', e)
    rewardRule.value = null
    rewardAmount.value = 0
  }
}

const confirmRecharge = async () => {
  const rewardText = rewardAmount.value > 0 ? ` (赠送奖励¥${formatAmount(rewardAmount.value)})` : ''
  const ok = window.confirm(`确认使用${displayMethod()}充值 ¥${formatAmount(amount.value)}${rewardText} 吗？`)
  if (!ok) return
  await simulateThirdParty()
  const res = await walletApi.recharge({ amount: amount.value, remark: `充值-${method.value}` })
  lastTxn.value = res
  await router.push('/wallet')
}

const displayMethod = () => ({ alipay: '支付宝', wechat: '微信支付', card: '银行卡' }[method.value])

const simulateThirdParty = () => new Promise(resolve => setTimeout(resolve, 1000))
const goBack = () => router.push('/wallet')

// 初始化检查奖励规则
checkReward()

// 监听金额变化
watch(amount, checkReward)
</script>

<style scoped>
.wrapper { width: 100%; min-height: 100%; }
header { width: 100%; height: 12vw; background-color: #0097ff; color: #fff; font-size: 4.8vw; position: fixed; left: 0; top: 0; z-index: 1000; display: flex; justify-content: center; align-items: center; }
header i { position: absolute; left: 3vw; font-size: 6vw; color: #fff; cursor: pointer; }
.content { margin-top: 14vw; padding: 4vw; }
.section { margin-bottom: 6vw; }
.title { font-size: 4vw; color: #666; margin-bottom: 2vw; }
.presets { display: flex; gap: 3vw; margin-bottom: 3vw; }
.presets button { height: 10vw; border: 1px solid #ddd; border-radius: 2vw; background: #fff; padding: 0 4vw; }
.presets button.active { border-color: #0097ff; color: #0097ff; }
input { width: 100%; height: 10vw; border: 1px solid #ddd; border-radius: 2vw; padding: 0 3vw; font-size: 4vw; }
.methods { display: flex; gap: 6vw; font-size: 4vw; }
.confirm { width: 100%; height: 10vw; border: none; border-radius: 2vw; background: #38ca73; color: #fff; font-size: 4vw; font-weight: 700; }
.result { background: #f7f7f7; border-radius: 2vw; padding: 3vw; font-size: 4vw; }
.reward-info { margin-top: 3vw; padding: 3vw; background: linear-gradient(135deg, #fff5f5, #fff); border-radius: 2vw; border-left: 4px solid #38ca73; }
.reward-info.no-reward { border-left-color: #ccc; background: #f5f5f5; }
.reward-text { font-size: 4.2vw; font-weight: 600; color: #38ca73; margin-bottom: 1vw; }
.reward-info.no-reward .reward-text { color: #999; }
.reward-desc { font-size: 3.6vw; color: #666; }
</style>
